package com.gmall.common.util;


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
 * Project:gmall-common
 * File: com.gmall.cloud.common.core.util
 *
 * @author : hl.wu
 * @date : 2019-05-27
 */

/**
 * 高并发场景下System.currentTimeMillis()的性能问题的优化
 * 时间戳打印建议使用
 *
 * @author hl.wu
 */
public class CurrentTimeUtils {
    private static final String THREAD_NAME = "currentTime.clock";

    private static final CurrentTimeUtils MILLIS_CLOCK = new CurrentTimeUtils(1);

    private final long precision;

    private final AtomicLong now;

    private CurrentTimeUtils(long precision) {
        this.precision = precision;
        now = new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdating();
    }

    public static CurrentTimeUtils millisClock() {
        return MILLIS_CLOCK;
    }

    public static void main(String[] args) {
        System.out.println(CurrentTimeUtils.millisClock().now());
    }

    private void scheduleClockUpdating() {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
            Thread thread = new Thread(runnable, THREAD_NAME);
            thread.setDaemon(true);
            return thread;
        });
        scheduler.scheduleAtFixedRate(() ->
                now.set(System.currentTimeMillis()), precision, precision, TimeUnit.MILLISECONDS);
    }

    public long now() {
        return now.get();
    }

}
